package com.example.demo.configuration.inter;

import com.example.demo.SpringUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义展示序列化类
 */
@Component
public class CustomNumberSerializer extends NumberSerializer  {

    public CustomNumberSerializer() {
        super(Number.class);
    }

    public CustomNumberSerializer(Class<? extends Number> rawType) {
        super(rawType);
    }

    @Override
    public void serialize(Number value, JsonGenerator g, SerializerProvider provider) throws IOException {
        ShowRuleHandler showRuleHandler = SpringUtils.getBean(ShowRuleHandler.class);
        Object objValue = g.getCurrentValue();
        String fieldName = g.getOutputContext().getCurrentName();
        String typCode = showRuleHandler.getTypeCodeValue(objValue);
        //无意义指标处理
        String invalidValue = showRuleHandler.getInvalidValue(typCode, fieldName);
        if(invalidValue != null){
            g.writeString(invalidValue);
        }else{
            super.serialize(value,g,provider);
        }

    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        ShowRuleHandler showRuleHandler = SpringUtils.getBean(ShowRuleHandler.class);
        if(showRuleHandler.isEnable()) {
            CustomNullSerializer customNullSerializer = SpringUtils.getBean(CustomNullSerializer.class);
            serializerProvider.setNullValueSerializer(customNullSerializer);
            return this;
        }
        return super.createContextual(serializerProvider,beanProperty);
    }

}